package com.wn.trade.service.impl;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wn.access.api.BankAccessApi;
import com.wn.common.model.dto.borrow.BorrowQuery;
import com.wn.common.model.dto.borrow.BorrowRecordDTO;
import com.wn.common.model.vo.borrow.BorrowRecordVo;
import com.wn.common.model.vo.user.TokenVo;
import com.wn.common.model.vo.user.UserInfoVo;
import com.wn.common.result.Result;
import com.wn.common.utils.GeneratorCodeUtil;
import com.wn.common.utils.Pages;
import com.wn.common.utils.TokenUtils;
import com.wn.system.api.UserApi;
import com.wn.trade.entity.BorrowRecord;
import com.wn.trade.mapper.BorrowRecordMapper;
import com.wn.trade.service.IBorrowRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author yellow Docter
 * @date 2023 -03-02
 * @desc
 */
@Service
public class BorrowRecordServiceImpl extends ServiceImpl<BorrowRecordMapper, BorrowRecord> implements IBorrowRecordService {

    @Autowired
    private UserApi userApi;

    @Autowired
    private BankAccessApi bankAccessApi;

    @Override
    public String addBorrowRecord(BorrowRecordDTO borrowRecordDTO) {
        //01 认证
        TokenVo tokenVo = TokenUtils.getTokenVo();

        //02 创建借款对象
        BorrowRecord borrowRecord = new BorrowRecord();

        String userId = tokenVo.getUserId();

        borrowRecord.setUserId(Long.parseLong(userId));
        borrowRecord.setBorrowRecordNo(GeneratorCodeUtil.generator("BO"));
        borrowRecord.setDescription("借款学习java");

        borrowRecord.setType("银行借款");

        //借款期限
        borrowRecord.setPeriod(borrowRecordDTO.getPeriod());

        //投资年化利率
        borrowRecord.setInvestRate(new BigDecimal("6"));

        //借款年化利率
        borrowRecord.setBorrowerRate(new BigDecimal("6"));

        // 平台佣金年化利率
        borrowRecord.setCommissionRate(new BigDecimal("10"));

        //还款方式
        borrowRecord.setRepaymentWay("ALL");

        //借款金额
        borrowRecord.setAmount(borrowRecordDTO.getAmount());

        //借款状态   0 未审核
        borrowRecord.setBorrowStatus("0");

        borrowRecord.setCreateDate(new Date());
        //借款确认时间
        borrowRecord.setModifyDate(new Date());

        //可用状态
        borrowRecord.setStatus(false);

        // 流水号
        borrowRecord.setReqCode(GeneratorCodeUtil.generator("BO"));

        //通过远程调用 获取 userInfoVo 信息
        UserInfoVo userInfoVo = userApi.findUserById(tokenVo.getPhone());
        //没有
        borrowRecord.setUserCode(userInfoVo.getUserCode());

        // 性别判断
        String sex = Integer.parseInt(userInfoVo.getIdentityCode()
                .substring(16, 17)) % 2 == 0 ? "女士" : "先生";

        QueryWrapper<BorrowRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(BorrowRecord::getUserId,
                Long.parseLong( tokenVo.getUserId()));

        //1600307131273248770
        int count = (int) (this.count(queryWrapper) + 1);
        String userName = userInfoVo.getUserName();
        //借款名称
        borrowRecord.setName(
                userName + sex
                        + "第" + count + "次借款");

        //03 保存
        save(borrowRecord);

        return "borrow success";
    }

    @Override
    public Pages<BorrowRecordVo> borrowSearch(BorrowQuery borrowQuery,Integer currentPage,Integer pageSize) {

        LambdaQueryWrapper<BorrowRecord> borrowRecordLambdaQueryWrapper = Wrappers.lambdaQuery(BorrowRecord.class);
        //条件判断
        if (borrowQuery.getBorrowStatus() != null) {
            borrowRecordLambdaQueryWrapper.eq(BorrowRecord::getBorrowStatus,borrowQuery.getBorrowStatus());
        }
        if (StringUtils.isNotEmpty(borrowQuery.getName() )) {
            borrowRecordLambdaQueryWrapper.like(BorrowRecord::getName,borrowQuery.getName());
        }

        if (borrowQuery.getStartPeriod() != null ){
            borrowRecordLambdaQueryWrapper.ge(BorrowRecord::getPeriod,borrowQuery.getStartPeriod());
        }

        if (borrowQuery.getEndPeriod() != null ){
            borrowRecordLambdaQueryWrapper.le(BorrowRecord::getPeriod,borrowQuery.getEndPeriod());
        }

        //封装 pages
        IPage<BorrowRecord> iPage = new Page<>(currentPage,pageSize);
        IPage<BorrowRecord> recordIPage = page(iPage, borrowRecordLambdaQueryWrapper);

        Pages<BorrowRecordVo> pages = new Pages<>();
        List<BorrowRecord> records = recordIPage.getRecords();

        // 使用hutool 工具 把   List<BorrowRecord> 中的对象 转成  List<BorrowRecordVo>
        List<BorrowRecordVo> list = BeanUtil.copyToList(records, BorrowRecordVo.class);

        pages.setPageNum(currentPage);
        pages.setPageSize(pageSize);
        pages.setTotal(recordIPage.getTotal());
        pages.setList(list);

        return pages;
    }

    @Override
    public String verifyStatus(Long borrowRecordId, String approveStatus) {

        //01  拿到 借款记录
        BorrowRecord borrowRecord = getById(borrowRecordId);

        //02  发送给代理  （bank-access-日志记录） 不需要 把整个记录发送到 bank-access 发送一个vo就可以
        BorrowRecordVo borrowRecordVo = BeanUtil.copyProperties(borrowRecord,BorrowRecordVo.class);
        Result<String> result = bankAccessApi.syncBorrowRecord(borrowRecordVo);

        //03  返回   修改  借款记录 的状态
        int code = result.getCode();
        if (code == 200){
            //进行同步
            update(Wrappers.lambdaUpdate(BorrowRecord.class)
                    .set(BorrowRecord::getBorrowStatus, approveStatus)
                    .eq(BorrowRecord::getId,borrowRecordId)
            );
        }

        return "borrow借款记录成功";
    }
}
